package net.lab1024.sa.base.config;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.deser.std.NumberDeserializers;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import com.fasterxml.jackson.databind.deser.std.NumberDeserializers;

import java.io.IOException;

@Configuration
public class JacksonConfig {


    @Bean
    @Primary
    public ObjectMapper objectMapper() {
        SimpleModule module = new SimpleModule();
        module.addDeserializer(Double.class, new NaNSafeDoubleDeserializer());

        return new ObjectMapper()
                .registerModule(new JavaTimeModule()) // 注册 Java 8 时
                .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
                .registerModule(module)
                .enable(JsonParser.Feature.ALLOW_NON_NUMERIC_NUMBERS)
                .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    }

    @Bean
    @Primary
    public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter(
            ObjectMapper objectMapper) {

        return new MappingJackson2HttpMessageConverter(objectMapper);
    }

    // 修复后的自定义反序列化器
    public static class NaNSafeDoubleDeserializer extends JsonDeserializer<Double> {

        private final NumberDeserializers.DoubleDeserializer stdDeserializer =
                new NumberDeserializers.DoubleDeserializer(Double.class, 0.0);

        @Override
        public Double deserialize(JsonParser p, DeserializationContext ctxt)
                throws IOException {

            // 尝试读取文本值
            if (p.getCurrentToken() == JsonToken.VALUE_STRING) {
                String value = p.getText().trim();
                if ("NaN".equalsIgnoreCase(value)) {
                    return null; // 或 Double.NaN 根据业务需要
                }
            }

            // 使用标准反序列化器处理其他情况
            return stdDeserializer.deserialize(p, ctxt);
        }
    }

}